import { useState, useEffect } from 'react'
import { NavLink } from 'react-router-dom'
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Button,
  Space,
  Table,
  Image,
  Switch,
  Pagination,
  Modal,
  Upload,
  message
} from 'antd'
import type { Swiper, SwiperQuery } from '@/types/swiper'
import {
  getSwiperList,
  addSwiper,
  updateSwiper,
  deleteSwiper
} from '@/api/swiper'
import type { ColumnsType } from 'antd/es/table'
import type { UploadFile } from 'antd/es/upload/interface'
import { PlusOutlined } from '@ant-design/icons'
import type { UploadProps } from 'antd/es/upload'

let bannerid = ''

export default function Swiper () {
  const [isClear, setIsClear] = useState(false)
  const [swiperList, setSwiperList] = useState([] as Swiper[])
  const [total, setTotal] = useState(0)
  const [swiperQuery, setSwiperQuery] = useState({
    page: 1,
    pageSize: 2,
    alt: '',
    link: ''
  } as SwiperQuery)
  const [modal, contextHolder] = Modal.useModal()

  const getSwiperListData = async () => {
    const res = await getSwiperList(swiperQuery)

    setSwiperList(res.data.items)
    setTotal(res.data.total)
  }

  useEffect(() => {
    getSwiperListData()
  }, [swiperQuery.page, swiperQuery.pageSize])

  useEffect(() => {
    if (isClear) {
      getSwiperListData()
    }
  }, [isClear])

  const clear = () => {
    setSwiperQuery({
      ...swiperQuery,
      alt: '',
      link: ''
    })

    setIsClear(true)
  }

  const columns: ColumnsType<Swiper> = [
    {
      title: '轮播图图片',
      dataIndex: 'img',
      render: img => {
        return <Image src={img} style={{ width: 50, height: 50 }} />
      }
    },
    {
      title: '跳转地址',
      dataIndex: 'link',
      render: link => {
        return (
          <a target='__blank' href={link}>
            {link}
          </a>
        )
      }
    },
    {
      title: '轮播图alt',
      dataIndex: 'alt'
    },
    {
      title: '状态',
      dataIndex: 'flag',
      render: flag => <Switch checked={flag} />
    },
    {
      title: '状态',
      render: (_, record) => (
        <>
          <Space>
            <Button type='primary' onClick={() => edit(record)}>
              修改
            </Button>
            <Button
              type='primary'
              danger
              onClick={async () => {
                try {
                  await modal.confirm({
                    title: '提示',
                    content: '确认退出吗?'
                  })

                  await deleteSwiper(record.bannerid)
                  setSwiperQuery({ ...swiperQuery, page: 1 })
                } catch (error) {}
              }}
            >
              删除
            </Button>
          </Space>
        </>
      )
    }
  ]

  /***************下面跟新增&修改有关*****************/
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [mode, setMode] = useState<'add' | 'edit'>('add')
  const [isChecked, setIsChecked] = useState(true)
  const [form] = Form.useForm()

  const edit = (swiper: Swiper) => {
    bannerid = swiper.bannerid
    setMode('edit')
    form.setFieldsValue(swiper)
    setFileList([{ uid: swiper.bannerid, name: swiper.img, url: swiper.img }])
    setIsModalOpen(true)
  }

  const handleOk = async () => {
    try {
      const results = await form.validateFields()

      if (mode === 'add') {
        await addSwiper(results)
      } else {
        results.bannerid = bannerid
        await updateSwiper(results)
      }

      // 提示
      message.success(mode === 'add' ? '新增成功~' : '修改成功~')
      // 关闭弹出框
      setIsModalOpen(false)
      // 重新查询数据
      getSwiperListData()
    } catch (error) {
      console.log('---error---', error)
    }
  }

  const handleCancel = () => {
    setMode('add')
    setFileList([]) // 图片列表设置为空
    form.resetFields() // 清空内容和清空校验
    setIsModalOpen(false)
  }

  /*************图片上传相关****************/
  const [fileList, setFileList] = useState<UploadFile[]>([])
  const [previewOpen, setPreviewOpen] = useState(false)
  const [previewImage, setPreviewImage] = useState('')
  // 图片预览
  const handlePreview = (file: UploadFile) => {
    console.log(file)
    setPreviewImage(file.url ?? file.response.fileUrl)
    setPreviewOpen(true)
  }
  // 图片发生了改变（新增上传、删除）
  const handleChange: UploadProps['onChange'] = ({
    fileList: newFileList,
    file
  }) => {
    // 1、给fileList赋值
    setFileList(newFileList)
    if (file.response) {
      // 2、给表单中的img属性也要赋值，这样校验才能通过
      form.setFieldValue('img', file.response.fileUrl)
    }

    if (file.status === 'removed') {
      form.setFieldValue('img', '')
      form.validateFields(['img'])
    }
  }

  return (
    <div>
      <Card>
        <Breadcrumb
          items={[
            {
              title: <NavLink to='/'>首页</NavLink>
            },
            {
              title: '轮播图管理'
            },
            {
              title: '轮播图列表'
            }
          ]}
        />
        <Form
          layout='inline'
          form={form}
          size='large'
          style={{ marginTop: 20 }}
        >
          <Form.Item label='跳转链接'>
            <Input
              placeholder='请输入跳转链接'
              value={swiperQuery.link}
              onChange={e =>
                setSwiperQuery({ ...swiperQuery, link: e.target.value })
              }
            />
          </Form.Item>
          <Form.Item label='图片alt'>
            <Input
              placeholder='请输入图片alt'
              value={swiperQuery.alt}
              onChange={e =>
                setSwiperQuery({ ...swiperQuery, alt: e.target.value })
              }
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type='default' onClick={clear}>
                清空
              </Button>
              <Button type='primary' onClick={getSwiperListData}>
                搜索
              </Button>
              <Button type='default' onClick={() => setIsModalOpen(true)}>
                +新增轮播图
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Card style={{ marginTop: 10 }}>
        <Table
          dataSource={swiperList}
          columns={columns}
          pagination={false}
          rowKey='bannerid'
        />
        <Pagination
          style={{ marginTop: 20, textAlign: 'center' }}
          current={swiperQuery.page}
          pageSize={swiperQuery.pageSize}
          total={total}
          showSizeChanger
          showQuickJumper
          pageSizeOptions={[1, 2, 5, 10]}
          showTotal={total => `共 ${total} 条`}
          onChange={(page, pageSize) => {
            setSwiperQuery({ ...swiperQuery, page, pageSize })
          }}
        />
      </Card>
      <Modal
        title={mode === 'add' ? '新增轮播图' : '修改轮播图'}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        width={600}
      >
        <Form
          size='large'
          form={form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          initialValues={{ flag: true }}
        >
          <Form.Item
            label='轮播图图片'
            name='img'
            rules={[{ required: true, message: '轮播图不能为空' }]}
          >
            <div>
              <Upload
                action={`${import.meta.env.VITE_BASEURL}file/upload`}
                listType='picture-card'
                fileList={fileList}
                onPreview={handlePreview}
                onChange={handleChange}
              >
                {fileList.length >= 1 ? null : <PlusOutlined />}
              </Upload>
              <Modal
                open={previewOpen}
                title='图片预览'
                footer={null}
                onCancel={() => setPreviewOpen(false)}
              >
                <img
                  alt='example'
                  style={{ width: '100%', height: 400 }}
                  src={previewImage}
                />
              </Modal>
            </div>
          </Form.Item>
          <Form.Item
            label='跳转链接'
            name='link'
            rules={[{ required: true, message: '跳转链接不能为空' }]}
          >
            <Input placeholder='请输入跳转链接' />
          </Form.Item>
          <Form.Item label='alt说明' name='alt'>
            <Input placeholder='请输入alt说明' />
          </Form.Item>
          <Form.Item label='状态' name='flag'>
            <Switch
              checked={isChecked}
              onChange={isChecked => setIsChecked(isChecked)}
            />
          </Form.Item>
        </Form>
      </Modal>
      {contextHolder}
    </div>
  )
}
